package thirdPartyUtils.netty;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.http.HttpClientCodec;
import io.netty.handler.codec.http.HttpContentDecompressor;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import io.netty.handler.ssl.SslContext;
import io.netty.handler.ssl.SslContextBuilder;
import io.netty.handler.ssl.util.InsecureTrustManagerFactory;
import lombok.extern.slf4j.Slf4j;

import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.URI;
import java.net.URL;
import java.util.Objects;

@Slf4j
public class Client {


    private String urlStr;


    public Client(String urlStr) {
        this.urlStr = urlStr;
    }


    public  void start() throws InterruptedException {

        //线程组
        EventLoopGroup group = new NioEventLoopGroup();
        //启动类
        Bootstrap bootstrap = new Bootstrap();
        try {
            InetSocketAddress inetAddress = null;
            URI uri = new URI(urlStr);
            if (Objects.isNull(uri)) {
                return ;
            }
            boolean isSSL = urlStr.contains("https");
            try {
                URL url = new URL(urlStr);
                String host = url.getHost();
                InetAddress address = InetAddress.getByName(host);
                if (!host.equalsIgnoreCase(address.getHostAddress())) {
                    //域名连接,https默认端口是443，http默认端口是80
                    inetAddress = new InetSocketAddress(address, isSSL ? 443 : 80);
                } else {
                    //ip+端口连接
                    int port = url.getPort();
                    inetAddress = InetSocketAddress.createUnresolved(host, port);
                }
            } catch (Throwable e) {
                log.error("请求地址不合法：" + e);
                return;
            }
            bootstrap.group(group)
                    .remoteAddress(inetAddress)
                    .channel(NioSocketChannel.class)
                    .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 10000)
                    .option(ChannelOption.TCP_NODELAY,true)
                    //长连接
                    .option(ChannelOption.SO_KEEPALIVE,true)
                    .handler(new LoggingHandler(LogLevel.ERROR))

                    .handler(new ChannelInitializer<Channel>() {
                        @Override
                        protected void initChannel(Channel channel) throws Exception {
                            System.out.println("channelCreated. Channel ID："+channel.id());
                            SocketChannel socketChannel = (SocketChannel) channel;
                            socketChannel.config().setKeepAlive(true);
                            socketChannel.config().setTcpNoDelay(true);
                            if (isSSL) { //配置Https通信
                                SslContext context = SslContextBuilder.forClient().trustManager(InsecureTrustManagerFactory.INSTANCE).build();
                                channel.pipeline().addLast(context.newHandler(channel.alloc()));
                            }
                            socketChannel.pipeline()
                                    //包含编码器和解码器
                                    .addLast(new HttpClientCodec())
                                    //聚合
                                    .addLast(new HttpObjectAggregator(1024 * 10 * 1024))
                                    //解压
                                    .addLast(new HttpContentDecompressor())
                                    //添加ChannelHandler
                                    .addLast(new ClientHandler());

                        }
                    });

            ChannelFuture channelFuture = bootstrap.connect().sync();
            channelFuture.channel().closeFuture().sync();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            group.shutdownGracefully();
        }
    }

    public static void main(String[] args) throws InterruptedException {
        for (int i = 0; i < 10; i++) {
            Client client = new Client("https://ug.baidu.com/mcp/pc/pcsearch");
            client.start();
        }
    }
}
